package cn.jtcoding.web.framework.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * Web层的日志切面类
 */
@Slf4j
@Aspect
@Component
public class SystemLogAspect {

	@Pointcut("execution(public * cn.jtcoding..*.controller..*.*(..))  || execution(public * cn.jtcoding..*.service..*.*(..))") // 所有子目和所有参数
	public void log() {
	}

	@Before("log()")
	public void doBefore(JoinPoint joinPoint) throws Exception {

	}

	@AfterReturning(returning = "result", pointcut = "log()")
	public void doAfterReturning(Object result) throws Exception {
	}

	@Around("log()")
	public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
		long startTime = System.currentTimeMillis();
		Object result = null;
		try {
			result = joinPoint.proceed();
			long endTime = System.currentTimeMillis();
			String tragetClassName = joinPoint.getSignature().getDeclaringTypeName();
			String methodName = joinPoint.getSignature().getName();
			log.info("CLASS_METHOD [{}.{}] cost : {} ms.", tragetClassName, methodName, endTime - startTime);
		} catch (Throwable e) {
			long endTime = System.currentTimeMillis();
			log.info("{} Use time : {} ms with exception : {}", joinPoint, endTime - startTime, e.getMessage());
			throw e;
		}
		return result;
	}

	@AfterThrowing(throwing = "ex", pointcut = "log()")
	public void doAfterThrowing(Throwable ex) {
		log.error("[EXCEPTION] : ", ex);
	}
}
